﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using zframe;

/// <summary>
/// 加载ab包
/// </summary>
public class LoadAssetBundleInLocal : MonoBehaviour
{
    public Image abImg;
    public Image abBtnImg;
    // Start is called before the first frame update
    void Start()
    {
        
        string path = GetAbPath("atlas_itembg.unity3d");
        AssetBundle ab = AssetBundle.LoadFromFile(path);    
        if (ab != null) {
            var assets = ab.LoadAllAssets<Sprite>();

            ZLogger.Log("assets="+ assets.Length);
            if (abImg!=null && assets.Length>0)
            {
                abImg.sprite = assets[0]; 
            }
        }
        path = GetAbPath("atlas_button.unity3d");
        ab = AssetBundle.LoadFromFile(path);
        Sprite btn = ab.LoadAsset<Sprite>("g-btn-blue-dn");
        if (abBtnImg!=null && btn!=null)
        {
            abBtnImg.sprite = btn;
        }
        //unity中加载二进制数据
        //请注意，带有 .txt 和 .bytes 扩展名的文件将分别视为文本文件和二进制文件。
        //不要尝试使用 .txt 扩展名来存储二进制文件，因为这样会在尝试从中读取数据时产生意外行为。
        path = GetAbPath("config_configs.unity3d");
        ab = AssetBundle.LoadFromFile(path);
        TextAsset config = ab.LoadAsset<TextAsset>("config");
        byte[] configBytes = config.bytes;
        MemoryStream stream = new MemoryStream();
        int statIdx = 0;
        var head = BitConverter.ToInt32(configBytes, statIdx);
        statIdx += 4;
        var mask = BitConverter.ToInt32(configBytes, statIdx);
        statIdx += 4;
        var tableCount = BitConverter.ToInt32(configBytes, statIdx);
        statIdx += 4;
        for (int i = 0; i < tableCount; i++)
        {
            var nameLen = BitConverter.ToUInt16(configBytes,statIdx);
            statIdx += 2;
            byte[] nameBytes = new byte[nameLen];
            Buffer.BlockCopy(configBytes, statIdx, nameBytes, 0, nameLen);
            statIdx += nameLen;
            string name = Encoding.UTF8.GetString(nameBytes);
            ZLogger.Log("name="+ name);
            break;
        }


    }

    private string GetAbPath(string name)
    {
        string path = Path.Combine(Application.dataPath, "abBuilds", name);
        return path;    
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
